package com.five.taotao.guide_mine;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.five.taotao.Adapter.ShopcarAdapter;

import com.five.taotao.Application.MyApplication;
import com.five.taotao.R;

import com.five.taotao.entity.ShoppingCart;
import com.five.taotao.order_details.OrderConfirmActivity;
import com.five.taotao.selfwidget.CustomProgressDialog;
import com.five.taotao.util.Constants;
import com.google.gson.Gson;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;

public class ShopCarActivity extends AppCompatActivity {
    private ListView listView;
    private ShopcarAdapter shopcarAdapter;
    private ShoppingCart.ListBean product;
    private List<ShoppingCart.ListBean> payData;
    private List<ShoppingCart.ListBean> delData;
    private TextView tv_shopcar_editor;
    private boolean editor_flag=false;
    private TextView tv_shopcar_money;
    private TextView tv_shopcar_money_w;
    private TextView tv_shopcar_topay;
    private CheckBox cb_shopcar_allselected;
    private List<ShoppingCart.ListBean> mData;
    private CustomProgressDialog myDialog;

    @OnClick(R.id.back)
    public void back() {
        finish();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_shop_car);
        ButterKnife.bind(this);
        listView= (ListView) findViewById(R.id.lv_shopcar);
        mData=new ArrayList<>();
        payData=new ArrayList<>();
        delData=new ArrayList<>();

        shopcarAdapter=new ShopcarAdapter(mData,this);
        listView.getItemAtPosition(2);
        listView.setAdapter(shopcarAdapter);

        loadData();

        tv_shopcar_money= (TextView) findViewById(R.id.tv_shopcar_money);//结算总价
        tv_shopcar_money_w= (TextView) findViewById(R.id.tv_shopcar_money_w);//“合计：”
        tv_shopcar_editor= (TextView) findViewById(R.id.tv_shopcar_editor);//编辑
        tv_shopcar_topay= (TextView) findViewById(R.id.tv_shopcar_topay);//支付、删除按钮
        cb_shopcar_allselected= (CheckBox) findViewById(R.id.cb_shopcar_allselected);//全选按钮
        shopcarAdapter.setOnShopcarListener(new ShopcarAdapter.ShopcarListener() {
            @Override
            public void select(final ShopcarAdapter.ViewHolder viewHolder, View view, int postion) {
                product=mData.get(postion);
                //判断结算栏是否显示
                for(int i=0;i<mData.size();i++){
                    if(mData.get(i).getIsSelected()){
                        viewHolder.end.setVisibility(View.VISIBLE);
                    }else{
                        viewHolder.end.setVisibility(View.GONE);
                    }
                }
                viewHolder.goods.setTag(postion);
                viewHolder.goods.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        CheckBox ch = (CheckBox) view;
                        int po = (int) ch.getTag();
                        if (ch.isChecked()) {
                            mData.get(po).setIsSelected(true);
                            viewHolder.goods.setChecked(mData.get(po).getIsSelected());
                            viewHolder.store.setChecked(mData.get(po).getIsSelected());
                            viewHolder.end.setVisibility(View.VISIBLE);
                            //如果editor_flag是true，则将选中的货物加到删除集合中，否则加到支付集合中
                            if(editor_flag){
                                delData.add(mData.get(po));
                                tv_shopcar_topay.setText("删除(" + delData.size() + ")");
                            }else{
                                payData.add(mData.get(po));//将选中的商品加到支付集合中
                                tv_shopcar_topay.setText("去支付("+payData.size()+")");
                                //同时更新总费用
                                double newMoney=sumCost(tv_shopcar_money,po,true);
                                tv_shopcar_money.setText("￥"+newMoney);

                            }
                        } else {
                            mData.get(po).setIsSelected(false);
                            viewHolder.goods.setChecked(mData.get(po).getIsSelected());
                            viewHolder.store.setChecked(mData.get(po).getIsSelected());
                            viewHolder.end.setVisibility(View.GONE);
                            //如果editor_flag是true，则将选中的货物加到删除集合中，否则加到支付集合中
                            if(editor_flag){
                                delData.remove(mData.get(po));
                                tv_shopcar_topay.setText("删除(" + delData.size() + ")");
                            }else{
                                payData.remove(mData.get(po));//将选中的商品从集合中去除
                                tv_shopcar_topay.setText("去支付(" + payData.size() + ")");
                                double newMoney=sumCost(tv_shopcar_money,po,false);
                                tv_shopcar_money.setText("￥"+newMoney);
                            }

                        }
                    }
                });
                viewHolder.goods.setChecked(product.getIsSelected());
                viewHolder.store.setChecked(product.getIsSelected());

                viewHolder.store.setTag(postion);
                viewHolder.store.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        CheckBox ch = (CheckBox) view;
                        int po = (int) ch.getTag();
                        if (ch.isChecked()) {
                            mData.get(po).setIsSelected(true);
                            viewHolder.goods.setChecked(mData.get(po).getIsSelected());
                            viewHolder.store.setChecked(mData.get(po).getIsSelected());
                            viewHolder.end.setVisibility(View.VISIBLE);
                            //如果editor_flag是true，则将选中的货物加到删除集合中，否则加到支付集合中
                            if(editor_flag){
                                delData.add(mData.get(po));
                                tv_shopcar_topay.setText("删除(" + delData.size() + ")");
                            }else{
                                payData.add(mData.get(po));//将选中的商品加到集合中
                                tv_shopcar_topay.setText("去支付(" + payData.size() + ")");
                                double newMoney=sumCost(tv_shopcar_money,po,true);
                                tv_shopcar_money.setText("￥"+newMoney);
                            }
                        } else {
                            mData.get(po).setIsSelected(false);
                            viewHolder.goods.setChecked(mData.get(po).getIsSelected());
                            viewHolder.store.setChecked(mData.get(po).getIsSelected());
                            viewHolder.end.setVisibility(View.GONE);
                            //如果editor_flag是true，则将选中的货物加到删除集合中，否则加到支付集合中
                            if(editor_flag){
                                delData.remove(mData.get(po));
                                tv_shopcar_topay.setText("删除(" + delData.size() + ")");
                            }else{
                                payData.remove(mData.get(po));//将选中的商品从集合中去除
                                tv_shopcar_topay.setText("去支付(" + payData.size() + ")");
                                double newMoney=sumCost(tv_shopcar_money,po,false);
                                tv_shopcar_money.setText("￥"+newMoney);
                            }
                        }
                    }
                });
                viewHolder.goods.setChecked(product.getIsSelected());
                viewHolder.store.setChecked(product.getIsSelected());
            }

            //减少商品
            @Override
            public void decGoods(final ShopcarAdapter.ViewHolder viewHolder, View view, int postion) {
                product=mData.get(postion);

                viewHolder.dec.setTag(postion);
                viewHolder.count.setTag(postion);
                viewHolder.dec.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        ImageView im = (ImageView) view;
                        int po = (int) im.getTag();
                        int tmp = mData.get(po).getNum() - 1;
                        if (tmp == 0) {
                            MyApplication.toast.toastShow("购买数量至少为一件");
                            return;
                        }
                        mData.get(po).setNum(mData.get(po).getNum() - 1);
                        viewHolder.count.setText(mData.get(po).getNum() + "");
                        viewHolder.count1.setText("已选" + mData.get(po).getNum() + "件商品,合计：");
                        viewHolder.cost.setText("￥" + mData.get(po).getNum() * mData.get(po).getVipprice());
                        if(mData.get(po).getIsSelected()){
                            //更新总费用
                            String oldMoney=tv_shopcar_money.getText().toString();//￥120
                            double money=Double.parseDouble(oldMoney.substring(1));
                            money-=mData.get(po).getVipprice();
                            tv_shopcar_money.setText("￥"+money);
                        }
                    }
                });
                viewHolder.count.setText(product.getNum() + "");
                viewHolder.count1.setText("已选" + product.getNum() + "件商品,合计：");
                viewHolder.cost.setText("￥" + product.getNum() * product.getVipprice());
            }

            //增加商品
            @Override
            public void incGoods(final ShopcarAdapter.ViewHolder viewHolder, View view, int postion) {
                product=mData.get(postion);

                viewHolder.inc.setTag(postion);
                viewHolder.count.setTag(postion);
                viewHolder.inc.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        ImageView im = (ImageView) view;
                        int po = (int) im.getTag();
                        mData.get(po).setNum(mData.get(po).getNum() + 1);
                        viewHolder.count.setText(mData.get(po).getNum() + "");
                        viewHolder.count1.setText("已选" + mData.get(po).getNum() + "件商品,合计：");
                        viewHolder.cost.setText("￥" + mData.get(po).getNum() * mData.get(po).getVipprice());
                        if(mData.get(po).getIsSelected()){
                            //更新总费用
                            String oldMoney=tv_shopcar_money.getText().toString();//￥120
                            double money=Double.parseDouble(oldMoney.substring(1));
                            money+=mData.get(po).getVipprice();
                            tv_shopcar_money.setText("￥"+money);
                        }
                    }
                });
                viewHolder.count.setText(product.getNum() + "");
                viewHolder.count1.setText("已选"+product.getNum()+"件商品,合计：");
                viewHolder.cost.setText("￥"+product.getNum()*product.getVipprice());
            }
        });

        //编辑、完成按钮
        tv_shopcar_editor.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (editor_flag) {
                    //更新后台
                    List<Integer> list=new ArrayList<>();
                    for (int i=0;i<delData.size();i++){
                        list.add(delData.get(i).getCarid());
                    }
                    //将购物城表中的数据删除
                    mData.removeAll(delData);
                    delData.clear();
                    shopcarAdapter.notifyDataSetChanged();

                    Gson gson=new Gson();
                    String g=gson.toJson(list);
                    OkHttpUtils
                            .post()
                            .url(Constants.SD_URL)
                            .addParams("carids", g)
                            .build()
                            .execute(new StringCallback() {
                                @Override
                                public void onError(Call call, Exception e, int id) {

                                }

                                @Override
                                public void onResponse(String response, int id) {
                                    if (delData.size() != 0) {
                                        MyApplication.toast.toastShow("删除成功");
                                    }
                                }
                            });
                    //更新前台
                    editor_flag = false;
                    tv_shopcar_editor.setText("编辑");
                    tv_shopcar_money.setVisibility(View.VISIBLE);//显示
                    tv_shopcar_money_w.setVisibility(View.VISIBLE);//显示
                    tv_shopcar_topay.setText("去支付(" + payData.size() + ")");
                    cb_shopcar_allselected.setChecked(false);


                } else {
                    editor_flag = true;
                    tv_shopcar_editor.setText("完成");
                    tv_shopcar_money.setVisibility(View.GONE);//隐藏
                    tv_shopcar_money_w.setVisibility(View.GONE);//隐藏
                    //将在支付页面已经选中的数据加到删除集合中
                    for (int i = 0; i < mData.size(); i++) {
                        if (mData.get(i).getIsSelected()) {
                            delData.add(mData.get(i));
                        }
                    }
                    //同时将支付集合中的数据清空
                    payData.clear();
                    tv_shopcar_money.setText("￥0.0");
                    tv_shopcar_topay.setText("删除(" + delData.size() + ")");
                }
            }
        });

        //支付或者删除

        tv_shopcar_topay.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(editor_flag){//删除
                    //更新后台
                    List<Integer> list=new ArrayList<>();
                    for (int i=0;i<delData.size();i++){
                        list.add(delData.get(i).getCarid());
                    }
                    Gson gson=new Gson();
                    String g=gson.toJson(list);
                    OkHttpUtils
                            .post()
                            .url(Constants.SD_URL)
                            .addParams("carids",g)
                            .build()
                            .execute(new StringCallback() {
                                @Override
                                public void onError(Call call, Exception e, int id) {
                                    MyApplication.toast.toastShow("网络异常");
                                }

                                @Override
                                public void onResponse(String response, int id) {
                                    MyApplication.toast.toastShow("删除成功");
                                }
                            });
                    mData.removeAll(delData);
                    delData.clear();
                    shopcarAdapter.notifyDataSetChanged();
                    tv_shopcar_topay.setText("删除("+delData.size()+")");
                }else{//支付
                    //跳转到支付界面
                    Log.e("支付",payData.size()+"");
                    Intent intent = new Intent(ShopCarActivity.this, OrderConfirmActivity.class);
                    Bundle bundle = new Bundle();
                    bundle.putSerializable("list",(Serializable)payData);
                    intent.putExtras(bundle);
                    startActivity(intent);
                }
            }
        });
        //全选按钮
        cb_shopcar_allselected.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                if(b){
                    double sum=0;
                    //将全部元素标记为已选
                    for(int i=0;i<mData.size();i++){
                        mData.get(i).setIsSelected(true);
                        sum+=mData.get(i).getVipprice()*mData.get(i).getNum();
                    }
                    shopcarAdapter.notifyDataSetChanged();
                    if(editor_flag){//全选加入删除集合
                        if(!delData.isEmpty()){//不是空集合，先清空
                            delData.clear();
                        }
                        delData.addAll(mData);
                        tv_shopcar_topay.setText("删除(" + delData.size() + ")");
                    }else{//全选加入支付集合
                        if(!payData.isEmpty()){
                            payData.clear();
                            Log.e("paysize",payData.size()+"");
                        }
                        payData.addAll(mData);
                        tv_shopcar_topay.setText("去支付("+payData.size()+")");
                    }
                    //同时更新总费用
                    tv_shopcar_money.setText("￥"+sum);
                }else{//全反选
                    for(int i=0;i<mData.size();i++){
                        mData.get(i).setIsSelected(false);
                    }
                    shopcarAdapter.notifyDataSetChanged();
                    if(editor_flag){
                        delData.clear();
                        tv_shopcar_topay.setText("删除(" + delData.size() + ")");
                    }else{
                        payData.clear();
                        tv_shopcar_topay.setText("去支付("+payData.size()+")");
                    }
                    //更新总费用
                    tv_shopcar_money.setText("￥0.0");
                }
            }
        });
    }

    /**
     *
     * @param tv_shopcar_money 已经选中商品总费用
     * @param po  选中的位置
     * @return
     */
    private double sumCost(TextView tv_shopcar_money,int po,boolean isselected){
        String oldMoney=tv_shopcar_money.getText().toString();//￥120
        double money=Double.parseDouble(oldMoney.substring(1));
        double vipprice=mData.get(po).getVipprice();
        int count=mData.get(po).getNum();
        if(isselected){
            return money+vipprice*count;
        }
        return money-vipprice*count;
    }
    private void loadData(){
        circle();
        OkHttpUtils
                .post()
                .url(Constants.SC_URL)
                .addParams("id", MyApplication.userId)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {

                    }

                    @Override
                    public void onResponse(String response, int id) {
                       /* Log.i("TAG", response);*/
                        Gson gson = new Gson();
                        ShoppingCart musicWebAlbum = gson.fromJson(response, ShoppingCart.class);
                        List<ShoppingCart.ListBean> items = musicWebAlbum.getList();
                        mData.clear();
                        mData.addAll(items);
                        shopcarAdapter.notifyDataSetChanged();
                        myDialog.dismiss();
                    }
                });
    }


    /**
     * 圆形进度条测试..
     */
    public void circle() {
        myDialog = new CustomProgressDialog(this,R.style.dialog);
        Window wd= myDialog.getWindow();
        WindowManager.LayoutParams lp = wd.getAttributes();
        lp.alpha = 0.9f;
        wd.setAttributes(lp);
        myDialog.show(); // 显示进度条
    }


}
